package com.success.application.ground.adapter;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.TextHttpResponseHandler;
import com.success.application.YuanbaoApplication;
import com.success.application.api.YuanbaoApi;
import com.success.application.base.BaseRecyclerViewAdapter;
import com.success.application.common.param.Params;
import com.success.application.common.result.Result;
import com.success.application.common.result.StringResult;
import com.success.application.ground.FriendFragment;
import com.success.application.ground.bean.Comment;
import com.success.application.ground.bean.Friend;
import com.success.application.ground.bean.Photo;
import com.success.application.ground.bean.Thumb;
import com.success.application.ground.bean.ThumbData;
import com.success.application.ground.cust_view.CusListView;
import com.success.application.ground.cust_view.HorizontalListView;
import com.success.application.ground.cust_view.HorizontalListViewAdapter;
import com.success.application.ground.holder.CommentHolder;
import com.success.application.ground.holder.FriendHolder;
import com.success.application.ground.holder.TopHolder;
import com.success.application.myapplication.R;
import com.success.application.user.AccountHelper;
import com.success.application.util.CommentBar;
import com.success.application.util.DialogHelper;
import com.success.application.widget.GsonUtils;
import com.success.application.widget.SimplexToast;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;
import static com.success.application.myapplication.R.id.tv_commment;
import static com.success.application.myapplication.R.id.tv_username_comment;

/**
 * Created by ChrisWong on 2017/1/17.
 */

public class FriendAdapter extends BaseRecyclerViewAdapter<Friend> {
    public static final int VIEW_TYPE_TOP = 99;
    public static final int VIEW_TYPE_NORMAL = 100;
    public static final int VIEW_TYPE_COMMENT = 98;
    HorizontalListViewAdapter hListViewAdapter;
    private PopupWindow mMorePopupWindow;
    private int mShowMorePopupWindowWidth;
    private int mShowMorePopupWindowHeight;
    public TextView tv_zan;
    //下方评论条
    private CommentBar mDelegation;
    //评论框
    EditText mViewInput;
    //弹框
    private Dialog dialog;
    protected Result<Map> result;
    private int dzType;
    private String dzId;//点赞id
    private String neirong;//评论内容
    Thumb thum;
    ImageView like;
    ImageView comment;


    public FriendAdapter(Context context, int mode) {
        super(context, mode);
        this.mContext = context;
    }
    protected Context mContext;//定义成protected,用来给子类访问

    @Override
    protected RecyclerView.ViewHolder onCreateDefaultViewHolder(ViewGroup parent, int viewType) {
//        如果是追加项，则打开滚动图
        if(viewType == VIEW_TYPE_TOP){
       //滚动图
            View v = mInflater.inflate(R.layout.ground_top,parent,false);
            return new TopHolder(v);
        } else{
            View v = mInflater.inflate(R.layout.shop_help_item_list,parent,false);
            return new FriendHolder(v);
        }
    }
    @Override
    public int getItemViewType(int position) {
        if (position == 0 && (BEHAVIOR_MODE == ONLY_HEADER || BEHAVIOR_MODE == BOTH_HEADER_FOOTER))
            return VIEW_TYPE_HEADER;
        if(mItems.size() > 0 && position == 0)
            return VIEW_TYPE_TOP;
        if (position + 1 == getItemCount() && (BEHAVIOR_MODE == ONLY_FOOTER || BEHAVIOR_MODE == BOTH_HEADER_FOOTER))
            return VIEW_TYPE_FOOTER;
        else{
            return VIEW_TYPE_NORMAL;
        }
    }
    //父类已自动绑定，若有特殊需求才需要继承方法
    @Override
    protected void onBindDefaultViewHolder(RecyclerView.ViewHolder holder, final Friend friend, int position) {
        super.onBindDefaultViewHolder(holder, friend, position);
        if (position >= 1) {
            final FriendHolder cHolder = (FriendHolder) holder;
            //图片列表
            List<Photo> photos = friend.getTplist();
            List<String> urlList = new ArrayList<String>();
            for(int i=0;i<photos.size();i++){
                urlList.add("http://47.92.92.215:8087"+photos.get(i).getTpUrl());
            }

            cHolder.layout.setUrlList(urlList);

            //评论列表
            List<Comment> comments = friend.getPllist();
            cHolder.cus_listView.setList(comments);
            cHolder.cus_listView.setTag(position);
            cHolder.cus_listView.setOnItemClickListener(new CusListView.OnItemClickListener() {
                @Override
                public void setCusOnItemClick(int positiion) {
                    Log.i("setCusOnItemClick", "-------------->  " + positiion);
                    //本人删除评论
                    //alert一下
                List<Comment> comments = friend.getPllist();
                    //如果是本人发的评论、可以进行删除
                    for(int i=0;i<comments.size();i++){
                        Comment com = comments.get(i);
                        if(com.getPl_plrid()!=null){
                            if ((int)Double.parseDouble(com.getPl_plrid())==((int) Double.parseDouble(AccountHelper.getUserId()))){
                                //点击是否进行删除
                                Params params = new Params();
                                params.put("id", Integer.valueOf(com.getId()));
                                YuanbaoApi.qxPl(params, new FriendAdapter.ShanChuFragmentHandler(positiion));
                            }
                        }
                    }
                }
            });
            List<Thumb> thumb = friend.getDzlist();
            String[] titles = new String[64];
            String[] ids = new String[64];
            if (thumb != null) {
                for (int i = 0; i < thumb.size(); i++) {
                    titles[i] = thumb.get(i).getUser_nc();
                    ids[i] = thumb.get(i).getUser_tx();
                }
            }

            //cHolder.horizon_listview.setAdapter(thumbs);
            hListViewAdapter = new HorizontalListViewAdapter(mContext, titles, ids);
            cHolder.horizon_listview.setAdapter(hListViewAdapter);
            cHolder.im_button.setTag(position);
            cHolder.cus_listView.setTag(position);
            cHolder.im_button.setOnClickListener(new FriendAdapter.XianShiClickListener() {
                @Override
                public void onClick(View v,int position) {
                    LayoutInflater li = (LayoutInflater) v.getContext().getSystemService
                            (Context.LAYOUT_INFLATER_SERVICE);
                    View content = li.inflate(R.layout.item_popip, null, false);
                    mMorePopupWindow = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    mMorePopupWindow.setBackgroundDrawable(new BitmapDrawable());
                    mMorePopupWindow.setOutsideTouchable(true);
                    mMorePopupWindow.setTouchable(true);
                    mMorePopupWindow.setFocusable(true);
                    content.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                    mShowMorePopupWindowWidth = content.getMeasuredWidth();
                    mShowMorePopupWindowHeight = content.getMeasuredHeight();
                    View parent = mMorePopupWindow.getContentView();
                    like = (ImageView) parent.findViewById(R.id.btn_zan);
                    like.setTag(position);
                    tv_zan = (TextView) parent.findViewById(R.id.tv_zan);
                    comment = (ImageView) parent.findViewById(R.id.btn_comment);
                    v.setTag(position);
                    comment.setTag(position);
                    List thumbs = friend.getDzlist();
                    if (thumbs != null) {
                        for (int i = 0; i < thumbs.size(); i++) {
                            //显示点赞人
                            Thumb thumb = (Thumb) thumbs.get(i);
                            try {
                                if ((int)Double.parseDouble(thumb.getUser_id())==((int) Double.parseDouble(AccountHelper.getUserId()))){
                                    dzType = 1;
                                }
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                        }
                        if (thumbs.size() == 0) {
                            dzType = 0;
                        }

                    } else {
                        dzType = 0;
                    }
                    //未点赞
                    if (dzType == 0) {
                        tv_zan.setText("赞");
                    } else {
                        tv_zan.setText("取消");
                    }

                    like.setOnClickListener(new FriendAdapter.XianShiClickListener() {
                        @Override
                        public void onClick(View v,int position) {
                            //进行点赞
                            mMorePopupWindow.dismiss();
                            if (AccountHelper.getUserId() != null && dzType == 0) {
                                Params params = new Params();
                                params.put("model.user_id", (int) Double.parseDouble(AccountHelper.getUserId()));
                                params.put("model.pyqId", (int) Double.parseDouble(friend.getId()));
                                YuanbaoApi.pubAddDz(params, new FriendAdapter.DianZanFragmentHandler(position));
                            } else {
                                //显示点赞人
                                for(int i=0;i<friend.getDzlist().size();i++){
                                    Thumb thumb =  friend.getDzlist().get(i);
                                    try {
                                        if(thumb.getUser_id()!=null){
                                            if ((int)Double.parseDouble(thumb.getUser_id())==((int) Double.parseDouble(AccountHelper.getUserId()))){
//                                                if(dzId==null){
                                                    if(thumb.getId()!=null){
                                                        dzId = thumb.getId();
                                                    }
//                                                }
                                                Params params = new Params();
                                                params.put("id", Integer.valueOf(dzId));
                                                YuanbaoApi.qxDz(params, new FriendAdapter.QuXiaoFragmentHandler(position));
                                            }
                                        }
                                    } catch (NumberFormatException e) {
                                        e.printStackTrace();
                                    }
                                }

                            }

                        }
                    });
                    comment.setTag(position);
                    comment.setOnClickListener(new FriendAdapter.XianShiClickListener(){
                        @Override
                        public void onClick(View v,int position) {
                            //进行评论
                            mMorePopupWindow.dismiss();
                            v.findViewById(R.id.btn_comment).setTag(position);
                            v.setTag(position);
                            mDelegation = CommentBar.delegation(v.getContext(), cHolder.mCoordinatorLayout);
                            mDelegation.mCoordinatorLayout.setTag(position);
                            mDelegation.mDelegation.mBtnCommit.setTag(position);
                            mDelegation.getBottomSheet().setCommitListener(new FriendAdapter.IndexFragmentClickListener(){
                                @Override
                                public void onClick(View v,int position) {
                                    v.setTag(position);
                                    String content = mDelegation.getBottomSheet().getCommentText().replaceAll("[\\s\\n]+", " ");
                                    if (TextUtils.isEmpty(content)) {
                                        SimplexToast.show(v.getContext(), "请输入文字");
                                        return;
                                    }
                                    dialog = DialogHelper.getProgressDialog(v.getContext(), "正在发表评论...");
                                    dialog.show();
                                    //封装参数

                                    if (AccountHelper.getUserId() != null) {
                                        Params params = new Params();
                                        params.put("model.pl_plrId", (int) Double.parseDouble(AccountHelper.getUserId()));
                                        params.put("model.pl_bplId", (int) Double.parseDouble(friend.getId()));
                                        params.put("model.pl_lx", 0);
                                        params.put("model.pl_zt", content);
                                        neirong =content;
                                        YuanbaoApi.addPl(params, new FriendAdapter.IndexFragmentHandler(position));
                                    }

                                }
                            });
                        }
                    });

                    //點擊
                    if (mMorePopupWindow == null) {
//                        mMorePopupWindow = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT,
//                                ViewGroup.LayoutParams.WRAP_CONTENT);
//                        mMorePopupWindow.setBackgroundDrawable(new BitmapDrawable());
//                        mMorePopupWindow.setOutsideTouchable(true);
//                        mMorePopupWindow.setTouchable(true);
//                        mMorePopupWindow.setFocusable(true);
//                        content.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
//                        mShowMorePopupWindowWidth = content.getMeasuredWidth();
//                        mShowMorePopupWindowHeight = content.getMeasuredHeight();
//                        View parent = mMorePopupWindow.getContentView();
//                        ImageView like = (ImageView) parent.findViewById(R.id.btn_zan);
//                        like.setTag(position);
//                        tv_zan = (TextView) parent.findViewById(R.id.tv_zan);
//                        ImageView comment = (ImageView) parent.findViewById(R.id.btn_comment);
                        //点赞的监听器
                        like.setOnClickListener(new FriendAdapter.XianShiClickListener() {
                            @Override
                            public void onClick(View v,int position) {
                                //进行点赞
                                mMorePopupWindow.dismiss();
                                if (AccountHelper.getUserId() != null && dzType == 0) {
                                    Params params = new Params();
                                    params.put("model.user_id", (int) Double.parseDouble(AccountHelper.getUserId()));
                                    params.put("model.pyqId", (int) Double.parseDouble(friend.getId()));
                                    YuanbaoApi.pubAddDz(params, new FriendAdapter.DianZanFragmentHandler(position));
                                } else {
                                        //显示点赞人
                                    for(int i=0;i<friend.getDzlist().size();i++){
                                        Thumb thumb =  friend.getDzlist().get(i);
                                        try {
                                            if(thumb.getUser_id()!=null){
                                                if ((int)Double.parseDouble(thumb.getUser_id())==((int) Double.parseDouble(AccountHelper.getUserId()))){
                                                    if(dzId==null){
                                                        if(thumb.getId()!=null){
                                                            dzId = thumb.getId();
                                                        }
                                                    }
                                                    Params params = new Params();
                                                    params.put("id", Integer.valueOf(dzId));
                                                    YuanbaoApi.qxDz(params, new FriendAdapter.QuXiaoFragmentHandler(position));
                                                }
                                            }
                                        } catch (NumberFormatException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }

                            }
                        });

                        // 评论的监听器
                        comment.setTag(position);
                        comment.setOnClickListener(new FriendAdapter.XianShiClickListener(){
                            @Override
                            public void onClick(View v,int position) {
                                //进行评论
                                mMorePopupWindow.dismiss();
                                v.findViewById(R.id.btn_comment).setTag(position);
                                v.setTag(position);
                                mDelegation = CommentBar.delegation(v.getContext(), cHolder.mCoordinatorLayout);
                                mDelegation.mCoordinatorLayout.setTag(position);
                                mDelegation.mDelegation.mBtnCommit.setTag(position);
                                mDelegation.getBottomSheet().setCommitListener(new FriendAdapter.IndexFragmentClickListener(){
                                    @Override
                                    public void onClick(View v,int position) {
                                        v.setTag(position);
                                        String content = mDelegation.getBottomSheet().getCommentText().replaceAll("[\\s\\n]+", " ");
                                        if (TextUtils.isEmpty(content)) {
                                            SimplexToast.show(v.getContext(), "请输入文字");
                                            return;
                                        }
                                        dialog = DialogHelper.getProgressDialog(v.getContext(), "正在发表评论...");
                                        dialog.show();
                                        //封装参数

                                        if (AccountHelper.getUserId() != null) {
                                            Params params = new Params();
                                            params.put("model.pl_plrId", (int) Double.parseDouble(AccountHelper.getUserId()));
                                            params.put("model.pl_bplId", (int) Double.parseDouble(friend.getId()));
                                            params.put("model.pl_lx", 0);
                                            params.put("model.pl_zt", content);
                                            neirong =content;
                                            YuanbaoApi.addPl(params, new FriendAdapter.IndexFragmentHandler(position));
                                        }

                                    }
                                });
                            }
                        });
                    } else {
                        mMorePopupWindow.dismiss();
                    }
                    if (mMorePopupWindow.isShowing()) {
                        mMorePopupWindow.dismiss();
                    } else {
                        int heightMoreBtnView = v.getHeight();
                        mMorePopupWindow.showAsDropDown(v, -mShowMorePopupWindowWidth,
                                -(mShowMorePopupWindowHeight + heightMoreBtnView) / 2);
                    }
                }

            });
        }
    }
    // 自定义加载添加评论监听器
    public class IndexFragmentHandler extends TextHttpResponseHandler {
        private int position;
        public IndexFragmentHandler(int position) {
            this.position = position;
        }
        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            try {
                ThumbData result = GsonUtils.fromJson(responseString, new TypeToken<ThumbData>() {
                }.getType());
                if(result.getResult().equals("success")){
                    dialog.dismiss();
                    mDelegation.getBottomSheet().dismiss();
                    //显示添加的评论一行
                    Friend t = getItem(position);
                    Comment comm = new Comment();
                    List list = t.getPllist();
                    comm.setId(String.valueOf(result.getData()));
                    comm.setUser_nc(AccountHelper.getUser().getUser_nc());
                    comm.setUser_tx(AccountHelper.getUser().getUser_tx());
                    comm.setPl_zt(neirong);
                    list.add(comm);
                    t.setPllist(list);
                    updateItem(position);
                    notifyDataSetChanged();
                }
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(statusCode, headers, responseString, e);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        }
    }

    private abstract class DianZanClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            onClick(v, Integer.parseInt(v.getTag().toString()));
        }

        public abstract void onClick(View v, int position);
    }

    private abstract class IndexFragmentClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            onClick(v, Integer.parseInt(v.getTag().toString()));
        }

        public abstract void onClick(View v, int position);
    }

    private abstract class XianShiClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            onClick(v, Integer.parseInt(v.getTag().toString()));
        }

        public abstract void onClick(View v, int position);
    }
    private abstract class QuXiaoClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            onClick(v, Integer.parseInt(v.getTag().toString()));
        }

        public abstract void onClick(View v, int position);
    }
    //自定义加载dianzzan监听器
    public class DianZanFragmentHandler extends TextHttpResponseHandler {
        private int position;
        public DianZanFragmentHandler(int position) {
            this.position = position;
        }
        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            try {
                ThumbData result = GsonUtils.fromJson(responseString, new TypeToken<ThumbData>() {
                }.getType());
                if(result.getResult().equals("success")){
                    dzType = 1;
                    tv_zan.setText("取消");
                    Friend t = getItem(position);
                    thum = new Thumb();
                    List list = t.getDzlist();
                    thum.setId(String.valueOf(result.getData()));
                    thum.setUser_id(AccountHelper.getUserId().toString());
                    thum.setUser_nc(AccountHelper.getUser().getUser_nc());
                    thum.setUser_tx(AccountHelper.getUser().getUser_tx());
                    list.add(thum);
                    t.setDzlist(list);
                    updateItem(position);

                }
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(statusCode, headers, responseString, e);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        }
    }
    //自定义加载d取消 监听器
    public class QuXiaoFragmentHandler extends TextHttpResponseHandler {
        private int position;
        public QuXiaoFragmentHandler(int position) {
            this.position = position;
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            try {
                Result<Map> result = GsonUtils.fromJson(responseString, new TypeToken<Result<Map>>() {
                }.getType());
                if(result.getResult().equals("success")){
                    dzType = 0;
                    tv_zan.setText("赞");
                    Friend t = getItem(position);
                    List list = t.getDzlist();
                    for (int i = 0; i < list.size(); i++) {
                        //显示点赞人
                        Thumb th = (Thumb) list.get(i);
                        if ((int)Double.parseDouble(th.getUser_id())==((int) Double.parseDouble(AccountHelper.getUserId()))){
                            list.remove(i);
                        }
                    }
                    t.setDzlist(list);
                    updateItem(position);
                }

            } catch (Exception e) {
                e.printStackTrace();
                onFailure(statusCode, headers, responseString, e);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        }
    }
    //删除
    public class ShanChuFragmentHandler extends TextHttpResponseHandler {
        private int position;
        public ShanChuFragmentHandler(int position) {
            this.position = position;
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            try {
                Friend t = getItem(position);
                List list = t.getPllist();
                list.remove(position);
                t.setPllist(list);
                updateItem(position);
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(statusCode, headers, responseString, e);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        }
    }

}
